import { defineStore } from 'pinia'
import axios from 'axios'
import router from '../router'

interface User {
  id: number
  username: string
  createTime: string
  updateTime: string
}

interface Role {
  id: number
  mark: string
  name: string
}

export const useUserStore = defineStore('user', {
  state: () => ({
    token: localStorage.getItem('token') || '',
    user: null as User | null,
    roles: [] as Role[],
    wsConnection: null as WebSocket | null,
    wsConnected: false,
  }),
  getters: {
    isLoggedIn: (state) => !!state.token,
  },
  actions: {
    async login(username: string, password: string) {
      try {
        const response = await axios.post('/api/auth/login', { username, password })
        const { Authorization } = response.data
        this.token = Authorization
        localStorage.setItem('token', Authorization) // 确保这行代码存在
        axios.defaults.headers.common['Authorization'] = Authorization
        await this.fetchUserInfo()
        this.connectWebSocket()
        router.push('/home')
        return true
      } catch (error) {
        console.error('Login failed:', error)
        return false
      }
    },
    async fetchUserInfo() {
      try {
        const response = await axios.get('/api/auth/userInfo')
        const { user, roles } = response.data
        this.user = user
        this.roles = roles
      } catch (error) {
        console.error('Failed to fetch user info:', error)
        throw error  // 重新抛出错误，以便在 App.vue 中捕获
      }
    },
    async logout() {
      try {
        await axios.post('/api/auth/logout')
        this.token = ''
        this.user = null
        this.roles = []
        localStorage.removeItem('token') // 确保这行代码存在
        delete axios.defaults.headers.common['Authorization']
        this.disconnectWebSocket()
        router.push('/login')
      } catch (error) {
        console.error('Logout failed:', error)
      }
    },
    connectWebSocket() {
      if (this.user && this.token) {
        const cleanToken = this.token.replace('Bearer ', '')
        const wsUrl = `ws://127.0.0.1:8080/api/ws/${this.user.username}/${cleanToken}`
        this.wsConnection = new WebSocket(wsUrl)

        this.wsConnection.onopen = () => {
          this.wsConnected = true
          console.log('WebSocket connected')
        }

        this.wsConnection.onclose = () => {
          this.wsConnected = false
          console.log('WebSocket disconnected')
        }

        this.wsConnection.onerror = (error) => {
          this.wsConnected = false
          console.error('WebSocket error:', error)
        }
      }
    },
    disconnectWebSocket() {
      if (this.wsConnection) {
        this.wsConnection.close()
        this.wsConnection = null
        this.wsConnected = false
      }
    },
    reconnectWebSocket() {
      this.disconnectWebSocket()
      this.connectWebSocket()
    },
  },
})
